//生成token包(npm i jsonwebtoken)
var jwt = require("jsonwebtoken")
var express = require("express")
var router = express.Router();
var { userModel } = require("../model/model");
var router = express.Router();
//腾讯人脸识别包(npm i tencentcloud-sdk-nodejs-iai)
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");
 
router.get('/test', (req, res) => {
    res.send({
        code: 200,
        msg: 'success'
    })
})
//人脸识别登录
router.post('/faceLogin', async (req, res) => {
    //获取前端传来的base64
    let b64 = req.body.b64
 
    const IaiClient = tencentcloud.iai.v20200303.Client;
 
    const clientConfig = {
        credential: {
            //自己的腾讯secretId
            secretId: "AKIDiKo594q33tuGYmxDcx6LWeaIo9HhElBQ",
            //自己的腾讯密匙
            secretKey: "DQWTGyVrKzqtvtumU0dFmt8cN7lOr8IQ",
        },
        region: "ap-beijing",  //地域参数（华北地区北京）
        profile: {
            httpProfile: {
                endpoint: "iai.tencentcloudapi.com",
            },
        },
    };
 
    const client = new IaiClient(clientConfig);
 
    const params = {
        "GroupIds": [  //你创建的人员库ID
            "miao"
        ],
        "Image": b64,  //图片的base64格式编码
        "NeedPersonInfo": 1,  //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
        "QualityControl": 0,  //图片质量控制。 0: 不进行控制； 1:较低的质量要求
        "FaceMatchThreshold": 85,  //人脸对比度设置为大于85才可
    };
 
    let doc = await client.SearchFaces(params)
 
    //doc为人脸识别后的返回信息
    console.log(doc.Results[0].Candidates[0].PersonId, 'doc');
    if (doc.Results[0].Candidates.length != 0) {  //表示当前人脸库有该人员
        let personName = doc.Results[0].Candidates[0].PersonName  //拿到该人员的名称
        console.log(personName, 'personNume');
 
        //生成token
        let token = jwt.sign({ "name": personName }, "face", { expiresIn: '1d' })
        res.send({
            code: 200,
            msg: "登录成功！",
            token,
            _id:doc.Results[0].Candidates[0].PersonId
        })
 
    } else {
        res.send({
            code: 401,
            msg: '人脸库无此人！'
        })
        return false
    }
 
})

module.exports = router;
